package top.lyjwn.ajui.widget.banner;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import top.lyjwn.ajui.R;

public class BannerIndicator extends View {
    private int number;
    private int position = 0;
    private int positionNum = 1;
    private Paint paint = new Paint();
    private int selectColor;
    private int unSelectColor;
    private float radius;
    private float space;


    private List<Integer> positions = new ArrayList<>();

    public BannerIndicator(Context context) {
        this(context, null);
    }

    public BannerIndicator(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.BannerIndicator);
        this.selectColor = typedArray.getColor(R.styleable.BannerIndicator_selectColor, Color.RED);
        this.unSelectColor = typedArray.getColor(R.styleable.BannerIndicator_unselectedColor, Color.BLACK);
        this.radius = typedArray.getDimension(R.styleable.BannerIndicator_radius, 10);
        this.space = typedArray.getDimension(R.styleable.BannerIndicator_space, 10);
        typedArray.recycle();

    }

    {
        paint.setStyle(Paint.Style.FILL);
        paint.setAntiAlias(true);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        float startPosition = getWidth() / 2 - (radius * 2 * number + space * (number - 1)) / 2;

        canvas.save();
        for (int i = 0; i < number; i++) {
            if (positions.size() > 1) {
                if (i == positions.get(0) || i == positions.get(1)) {
                    paint.setColor(selectColor);
                } else {
                    paint.setColor(unSelectColor);
                }
            } else {

                if ((positionNum>1 && (i == position || i < positionNum)) || (positionNum==1 && i == position)) {
                    paint.setColor(selectColor);
                } else {
                    paint.setColor(unSelectColor);
                }
            }

            canvas.drawCircle(startPosition + radius * (2 * i + 1) + i * space, getHeight() / 2, radius, paint);
        }
        canvas.restore();

    }

    public void setNumber(int number, int positionNum) {
        this.number = number;
        this.positionNum = positionNum;
    }

    public void setPosition(int... p) {
        positions.clear();
        for (int i = 0; i < p.length; i++) {
            positions.add(p[i]);
        }
        this.position = p[0];
        invalidate();
    }

}